<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Row :gutter="24" type="flex" class="optionList">
        <Col v-bind="grid">
          <Input
            @on-enter="searchData"
            v-model="ruleFrom.keyword"
            placeholder="请输入姓名/电话"
            :clearable="true"
            @on-clear="searchData"
          />
        </Col>
        <Col v-bind="grid">
          <Select
            @on-change="searchData"
            v-model="ruleFrom.clinic_id"
            placeholder="请选择诊室"
            :clearable="true"
          >
            <Option
              v-for="item in baseInfo.clinic"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </Col>
        <Col v-bind="grid">
          <Select
            @on-change="searchData"
            v-model="ruleFrom.department_id"
            placeholder="请选择部门"
            :clearable="true"
          >
            <Option
              v-for="item in baseInfo.department"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </Col>
        <Col v-bind="grid">
          <Select
            @on-change="searchData"
            v-model="ruleFrom.profession_id"
            placeholder="请选择岗位"
            :clearable="true"
          >
            <Option
              v-for="item in baseInfo.profession"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </Col>
        <Col v-bind="grid">
          <Select
            @on-change="searchData"
            v-model="ruleFrom.role_id"
            placeholder="请选择角色"
            :clearable="true"
          >
            <Option
              v-for="item in baseInfo.role"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </Col>
        <Col v-bind="grid" class="ivu-text-right">
          <Button type="primary" @click="handleAdd">新增</Button>
        </Col>
      </Row>
      <Table
        size="small"
        :columns="columns"
        :loading="loading"
        :data="data"
        class="ivu-mt-16"
      >
        <template slot-scope="{ row }" slot="status">
          <div class="status">
            <span
              :class="row.status === '1' ? 'radiusGreen' : 'radiusRed'"
            ></span>
            <span>{{ row.status === "1" ? "启用" : "停用" }}</span>
          </div>
          <!-- <Button
            v-if="row.status === '1'"
            type="success"
            size="small"
            @click="handleChangeStatus(row)"
            >启用</Button
          >
          <Button
            v-if="row.status === '0'"
            type="error"
            size="small"
            @click="handleChangeStatus(row)"
            >停用</Button
          > -->
        </template>
        <template slot-scope="{ row, index }" slot="operation">
          <a @click="handleUpdata(index)">编辑</a>
        </template>
      </Table>
      <div class="ivu-mt ivu-text-center">
        <Page
          :total="page.total"
          :current.sync="page.page"
          show-total transfer
          show-elevator
          :page-size="page.pageSize"
          @on-change="handleChangePage"
          :page-size-opts="pageOpts"
          show-sizer
          @on-page-size-change="changePageSize"
        />
      </div>
    </Card>
    <Modal
      v-model="creatModal"
      :title="title"
      width="800"
      :loading="creating"
      :mask-closable="false"
      @on-ok="handleSubmit"
      @on-cancel="handleCancel"
    >
      <Form
        :model="createData"
        ref="create"
        :rules="createRules"
        :label-width="80"
      >
        <Row :gutter="12">
          <Col span="12">
            <FormItem label="姓名" required prop="name">
              <Input
                v-model="createData.name"
                placeholder="请输入"
                clearable
              ></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="手机号" required prop="mobile">
              <Input
                v-model="createData.mobile"
                placeholder="请输入"
                clearable
              ></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="性别">
              <RadioGroup v-model="createData.gender">
                <Radio label="1">男</Radio>
                <Radio label="2">女</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="岗位" required prop="profession_id">
              <Select
                v-model="createData.profession_id"
                clearable
                @on-change="handleChangeProfession"
              >
                <Option
                  v-for="item in professionList"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.title }}</Option
                >
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="12">
          <Col span="12">
            <FormItem label="部门" prop="department_id">
              <Select v-model="createData.department_id" clearable>
                <Option
                  v-for="item in departmentList"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.title }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="角色" required prop="role_id">
              <Select v-model="createData.role_id" multiple>
                <Option
                  v-for="item in roleList"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.title }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="治疗室" v-if="+createData.profession_id === 300">
              <Select
                v-model="createData.room_id" multiple clearable>
                <Option
                  v-for="item in clinic_room" :key="item.value" :value="item.value" >{{ item.title }}</Option >
              </Select>
            </FormItem>
            <FormItem v-else label="诊室" prop="clinic_id">
              <Select
                v-model="createData.clinic_id"
                clearable
                :disabled="!clinicType"
              >
                <Option
                  v-for="item in clinicList"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.title }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="帐号" prop="user_name">
              <Input disabled v-model="createData.mobile"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="密码" prop="password">
              <Input v-model="createData.password" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="确认密码" prop="password_re">
              <Input
                v-model="createData.password_re"
                placeholder="请输入"
              ></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="状态">
              <i-switch
                v-model="createData.status"
                :before-change="handleBeforeChange"
              >
                <span slot="open">On</span>
                <span slot="close">Off</span>
              </i-switch>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  </div>
</template>

<script>
    import {
        GetPeople,
        UpdateMemberStatus,
        AddPeople,
        DetailPeople,
        UpdataPeople
    } from '@/api/setting';
    export default {
        name: 'diagnosis',
        data () {
            return {
                creatModal: false,
                loading: false,
                pageOpts: [10, 20, 30, 50],
                ruleFrom: {
                    keyword: '',
                    clinic_id: '',
                    department_id: '',
                    profession_id: '',
                    role_id: ''
                },
                baseInfo: {
                    clinic: [], // 诊室
                    department: [], // 部门
                    profession: [], // 岗位
                    role: [] // 角色
                },
                createData: {
                    room_id: [],
                    name: '',
                    mobile: '',
                    gender: '',
                    profession_id: '',
                    department_id: '',
                    role_id: [],
                    clinic_id: '',
                    status: true,
                    user_name: '',
                    password: '',
                    password_re: ''
                },
                department_id: '',
                role_id: '',
                clinicType: false,
                medical_id: 0,
                roleList: [],
                clinicList: [],
                clinic_room: [],
                departmentList: [],
                professionList: [],
                title: '',
                page: {
                    page: 1,
                    pageSize: 10,
                    total: 0
                },
                creating: true,
                createRules: {
                    name: [
                        {
                            required: true,
                            message: '请输入部门名称',
                            trigger: 'blur'
                        }
                    ],
                    mobile: [
                        {
                            message: '手机号格式不正确',
                            pattern: /^1[3456789]\d{9}$/,
                            trigger: 'blur'
                        }
                    ],
                    profession_id: [
                        {
                            required: true,
                            message: '请选择岗位',
                            trigger: 'blur'
                        }
                    ],
                    role_id: [
                        {
                            required: true,
                            message: '请选择角色',
                            type: 'array',
                            trigger: 'change'
                        }
                    ]
                },
                columns: [
                    {
                        title: '名称',
                        key: 'name'
                    },
                    {
                        title: '手机号',
                        key: 'mobile'
                    },
                    {
                        title: '部门',
                        key: 'department_name'
                    },
                    {
                        title: '诊室',
                        key: 'clinic_name'
                    },
                    {
                        title: '岗位',
                        key: 'profession_name'
                    },
                    {
                        title: '角色',
                        key: 'role_name'
                    },
                    {
                        title: '状态',
                        slot: 'status'
                    },
                    {
                        title: '操作',
                        slot: 'operation'
                    }
                ],
                data: [],
                grid: {
                    xl: 4,
                    lg: 8,
                    md: 12,
                    sm: 24,
                    xs: 24
                },
                status: true,
                profession_id: ''
            };
        },
        mounted () {
            this.ruleFrom.department_id = window.localStorage.getItem('departmentID');
            this.ruleFrom.role_id = window.localStorage.getItem('roleID');
            this.getData();
        },
        destroyed () {
            if (this.ruleFrom.department_id) {
                window.localStorage.removeItem('departmentID');
            }
            if (this.ruleFrom.role_id) {
                window.localStorage.removeItem('roleID');
            }
        },
        methods: {
            // 点击编辑里面的弹窗里面切换状态开关
            handleBeforeChange () {
                let flag = this.createData.status;
                return new Promise((resolve) => {
                    this.$Modal.confirm({
                        title: '切换人员状态',
                        content: flag
                            ? '确定停用当前人员？停用之后，患者清空，释放到公海'
                            : '确定启用当前人员',
                        onOk: () => {
                            resolve();
                        }
                    });
                });
            },
            // 获取数据
            getData () {
                this.loading = true;
                const config = Object.assign(
                    {
                        page: this.page.page,
                        pageSize: this.page.pageSize
                    },
                    this.ruleFrom
                );
                GetPeople(config)
                    .then((res) => {
                        this.data = res.list;
                        this.page.total = res.total;
                        if (this.status) {
                            this.baseInfo.clinic = res.condition.clinic_list || [];
                            this.baseInfo.department = res.condition.department_list;
                            this.baseInfo.profession = res.condition.profession_list;
                            this.baseInfo.role = res.condition.role_list;
                            this.status = false;
                        }
                    })
                    .finally(() => {
                        this.loading = false;
                });
            },
            handleChangeProfession (e) {
                if (this.profession_id == 302 || this.profession_id == 301) {
                  this.$Modal.confirm({
                      title: '更换岗位',
                      content: '确定修改当前人员岗位，修改后，患者清空，释放到公海',
                      onOk: () => {
                          if (e === this.medical_id.toString()) {
                              this.clinicType = true;
                          } else {
                              this.clinicType = false;
                              this.createData.clinic_id = '';
                          }
                      },
                      onCancel: () => {
                        this.createData.profession_id = this.profession_id
                      }
                  });
                } else if (e === '301') {
                  this.clinicType = true;
                } else this.clinicType = false;
            },
            // 新增
            handleAdd () {
                this.updateIndex = -1;
                this.title = '新增';
                this.$nextTick(() => {
                    this.$refs['create'].resetFields();
                });
                this.handlePeopleDetail(0);
            },
            // 状态切换
            handleChangeStatus (row) {
                this.$Modal.confirm({
                    title: '切换人员状态',
                    content: '确定' + (row.status === '1' ? '停用' : '启用') + '当前人员?',
                    onOk: () => {
                        UpdateMemberStatus({
                            id: row.id,
                            status: row.status === '1' ? '0' : '1'
                        }).then(() => {
                            this.$Message.success('修改成功');
                            this.getData();
                        });
                    }
                });
            },
            // 切换分页
            handleChangePage (e) {
                this.page.page = e;
                this.getData();
            },
            changePageSize (e) {
                this.page.pageSize = e;
                this.getData();
            },
            handleUpdata (index) {
                this.title = '编辑';
                this.$nextTick(() => {
                    this.$refs['create'].resetFields();
                    this.updateIndex = index;
                    const item = this.data[index];
                    this.handlePeopleDetail(item.id);
                    this.createData.id = item.id;
                });
            },
            // 获取详情
            handlePeopleDetail (id) {
                this.profession_id = ''
                this.creatModal = true;
                this.clinicType = false
                this.$nextTick(() => {
                    DetailPeople({ id }).then((res) => {
                        this.roleList = res.roleList;
                        this.clinicList = res.clinic;
                        this.clinic_room = res.clinic_room
                        this.medical_id = res.medical_id;
                        this.departmentList = res.department;
                        this.professionList = res.profession;
                        if (res.info && res.info !== null) {
                            for (let key in this.createData) {
                                this.createData[key] = res.info[key];
                            }
                            if (this.createData.profession_id === this.medical_id.toString()) {
                                this.clinicType = true;
                            } else {
                                this.clinicType = false;
                            }
                            this.createData.status = this.createData.status === '1';
                            if (res.info.role && res.info.role.length > 0) {
                                this.createData.role_id = res.info.role;
                            }
                            if (res.info.room && res.info.room.length > 0) {
                                this.createData.room_id = res.info.room;
                            }
                            this.profession_id = res.info.profession_id
                        }
                    });
                });
            },
            handleCancel() {
              this.profession_id = ''
            },
            handleSubmit () {
                this.$refs.create.validate((valid) => {
                    if (valid) {
                        let sendData = JSON.parse(JSON.stringify(this.createData));
                        sendData.status = sendData.status === true ? '1' : '0';
                        if (sendData.role_id && sendData.role_id.length > 0) {
                            sendData.role_id = sendData.role_id.join(',');
                        }
                        if (sendData.room_id && sendData.room_id.length > 0) {
                            sendData.room_id = sendData.room_id.join(',');
                        }
                        if (JSON.stringify(sendData.room_id) === '[]') sendData.room_id=''
                        sendData.user_name = sendData.mobile;
                        if (this.updateIndex < 0) {
                            // 新建
                            AddPeople(sendData).then(() => {
                                this.creatModal = false;
                                this.profession_id = ''
                                this.getData();
                                this.$Message.success('创建人员成功');
                            });
                        } else {
                            // 修改
                            UpdataPeople(sendData).then(() => {
                                this.creatModal = false;
                                this.profession_id = ''
                                this.getData();
                                this.$Message.success('修改人员信息成功');
                            });
                        }
                        this.creating = false;
                        this.$nextTick(() => {
                            this.creating = true;
                        });
                    } else {
                        this.creating = false;
                        this.$nextTick(() => {
                            this.creating = true;
                        });
                    }
                });
            },
            searchData () {
              this.page.page = 1
                this.getData();
            }
        }
    };
</script>
<style scoped>
/deep/.optionList .ivu-col {
  margin-bottom: 24px;
}
.status {
  display: flex;
  align-items: center;
}
.radiusRed {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: red;
  margin-right: 8px;
}
.radiusGreen {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: #49BF8D;
  margin-right: 8px;
}
</style>
